/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-11-10
 * Time: 23:16
 */
public class Solution {
    public int minOperations(int[] nums, int x) {
        int len = nums.length;
        int[] prefix = new int[len+1];
        int[] suffix = new int[len+1];
        // 前缀和
        for (int i = 1; i <= len; i++) {
            prefix[i] = prefix[i-1] + nums[i-1];
        }
        // 后缀和
        for (int i = len-1; i >= 0; i--) {
            suffix[i] = suffix[i+1] + nums[i];
        }
        int min = len + 1;
        int pos = 0;
        // 双指针
        for (int i = 0; i < len; i++) {
            pos = Math.max(pos, i);
            while (pos <= len && prefix[i] + suffix[pos] > x) {
                pos++;
            }
            if (pos <= len && prefix[i] + suffix[pos] == x) {
                min = Math.min(min, i+len-pos);
            }
        }
        return min > len ? -1 : min;
    }
}
